package com.shanghai.shanghaielectric.UI.chart;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.shanghai.shanghaielectric.Model.EventBus.EventBusModel_Date;
import com.shanghai.shanghaielectric.Model.ReportDateModel;
import com.shanghai.shanghaielectric.Model.db.ReportDateModel_1day;
import com.shanghai.shanghaielectric.R;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Alert;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_datePickUtil;
import com.shanghai.shanghaielectric.UI.chart.hellochart.LineChart;
import com.shanghai.shanghaielectric.UI.chart.widget.LegendEntity;
import com.shanghai.shanghaielectric.UI.chart.widget.LineChartEntity;
import com.shanghai.shanghaielectric.UI.refreshView.MyAdapter_report;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import lecho.lib.hellocharts.view.LineChartView;
import shanghaielectric_lib.Utils.ColorGenerator;
import shanghaielectric_lib.Utils.DateUtil;

/**
 * 事件-警告界面
 */
public class ChartFragment_chart extends Fragment implements SwipeRefreshLayout.OnRefreshListener, OnClickListener {
    public View chartView;
    @BindView(R.id.charts_type_spinner)
    Spinner chartsTypeSpinner;
    @BindView(R.id.charts_time)
    TextView chartsTime;
    @BindView(R.id.charts_check_1)
    CheckBox chartsCheck1;
    @BindView(R.id.charts_check_2)
    CheckBox chartsCheck2;
    @BindView(R.id.charts_check_3)
    CheckBox chartsCheck3;
    @BindView(R.id.charts_check_4)
    CheckBox chartsCheck4;
    @BindView(R.id.charts_check_5)
    CheckBox chartsCheck5;
    @BindView(R.id.charts_check_6)
    CheckBox chartsCheck6;
    @BindView(R.id.charts_check_ll)
    LinearLayout chartsCheckLl;
    @BindView(R.id.charts_max)
    CheckBox chartsMax;
    @BindView(R.id.charts_min)
    CheckBox chartsMin;
    @BindView(R.id.charts_avg)
    CheckBox chartsAvg;
    @BindView(R.id.charts_chart)
    LineChartView chartsChart;

    @BindView(R.id.data_charts_draw)
    TextView dataChartsDraw;
    Unbinder unbinder;
    private RadioGroup tabs_warning_rg;
    private LayoutInflater myInflater;
    private Context mContext;
    public MyAdapter_report mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private List<ReportDateModel> reportInfoModelList;
    List<CheckBox> checkBoxList;

    List<LegendEntity> legendEntities = new ArrayList<>();
    String[] powerFactor_array = new String[]{"A相电网功率因数", "B相电网功率因数", "C相电网功率因数", "A相负载功率因数", "B相负载功率因数", "C相负载功率因数"};
    String[] activePower_array = new String[]{"A相电网有功功率", "B相电网有功功率", "C相电网有功功率"};
    String[] reactivePower_array = new String[]{"A相电网无功功率", "B相电网无功功率", "C相电网无功功率"};
    List<String[]> list_arrays = new ArrayList<>();
    List<String> list_arrays_selected = new ArrayList<>();
    int currentArrayID = 0;//用于记录当前采用的字符串数组

    String startDate = DateUtil.getSystemTime_yyyy_MM_dd().substring(0, 7);

    LineChartView lineChartView;
    LinearLayout legend_view;
    LineChart lineChart;

    String mTitleX, mTitleY;
    int[] colors = ColorGenerator.getRandomColors();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println("EventWarning____onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        System.out.println("EventWarning____onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("EventWarning____onCreateView");
        chartView = inflater.inflate(R.layout.fragment_data_charts, container, false);
        mContext = getActivity().getApplicationContext().getApplicationContext();
        unbinder = ButterKnife.bind(this, chartView);
        lineChartView = (LineChartView) chartView.findViewById(R.id.charts_chart);
        legend_view = (LinearLayout) chartView.findViewById(R.id.legend_view);
        initData();
        initView();
        initListener();
//        initView();
//        for (int i = 0; i < 300; i++) {
//            myLineBlue.add(i, i);
//            myLineRed.add(i, 300 - i);
//            lineLineChart.getLines();
//
//        }


        return chartView;
    }

    private void initLine() {
        List<LineChartEntity> lineChartEntityList = new ArrayList<>();


        List<List<Double>> lists = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            List<Double> list_y = new ArrayList<>();
            list_y.add(10.2 + i * 10);
            list_y.add(15.2 + i * 10);
            list_y.add(18.0 + i * 10);
            list_y.add(20.2 + i * 10);
            list_y.add(5.2 + i * 10);
            list_y.add(40.2 + i * 10);
            list_y.add(70.2 + i * 10);
            lists.add(list_y);
        }
        List<Integer> list_x = new ArrayList<>();
        list_x.add(4);
        list_x.add(5);
        list_x.add(6);
        list_x.add(7);
        list_x.add(8);
        list_x.add(9);
        list_x.add(10);

        for (int i = 0; i < 5; i++) {
            LineChartEntity lineChartEntity = new LineChartEntity();
            Random random = new Random();
            int r = random.nextInt(256);
            int g = random.nextInt(256);
            int b = random.nextInt(256);
            lineChartEntity.setColor(Color.rgb(r, g, b));
            lineChartEntity.setxAxisValue(list_x);
            lineChartEntity.setyAxisValue(lists.get(i));
            lineChartEntityList.add(lineChartEntity);
        }
        lineChart = new LineChart(chartsChart, "日期（日）", "Y轴（单位）", lineChartEntityList);
    }

    private void drawLineChart(final LineChartView lineChartView, final String title_x, final String title_y) {


        String mStartDate = DateUtil.transferStringDate_yyyy_MM_dd_long(startDate + "-00") + "";//2018-01-00
        String mEndDate = DateUtil.getNextMonth(startDate + "-00") + "";
        Log.e("timecc", "" + mStartDate + "______" + mEndDate);
        /**
         * 查询 当月1 day  表里数据
         * */
        DataSupport.where("date > ? and date < ?", mStartDate, mEndDate).findAsync(ReportDateModel_1day.class).listen(new FindMultiCallback() {

            @Override
            public <T> void onFinish(List<T> t) {
                if (t.size()!=0) {
                    List<ReportDateModel_1day> reportDateModel1days = (List<ReportDateModel_1day>) t;

                    Log.e("reroer1day", "" + reportDateModel1days);
                    List<LineChartEntity> lineChartEntityList = getLineChartEntityList(reportDateModel1days, legendEntities);

                    lineChart = new LineChart(lineChartView, title_x, title_y, lineChartEntityList);
                }else {
                    Toast.makeText(mContext,"该月份暂时无数据",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private List<LineChartEntity> getLineChartEntityList(List<ReportDateModel_1day> reportDateModel1days, List<LegendEntity> legendEntityList) {
        List<Integer> xValues = new ArrayList<>();
        String[] legengArrayAll = new String[18];
        List<LineChartEntity> lineChartEntityList = new ArrayList<>();

        for (int i = 0, length = reportDateModel1days.size(); i < length; i++) {//验证是否是顺序的
            xValues.add(DateUtil.getDayFromDate(new Date(reportDateModel1days.get(i).date)));
        }

        for (int i = 0, length1 = legendEntityList.size(); i < length1; i++) {//最多18个图例,遍历图例根据name 确定lineChartEntityList成员位置
            List<Double> yValues = new ArrayList<>();
            LineChartEntity lineChartEntity = new LineChartEntity();
            String currentName = legendEntityList.get(i).name;
            if (currentName.equals("A相电网功率因数最大值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_Max_A());
                }
            } else if (currentName.equals("B相电网功率因数最大值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_Max_B());
                }
            } else if (currentName.equals("C相电网功率因数最大值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_Max_C());
                }
            } else if (currentName.equals("A相电网功率因数最小值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_Min_A());
                }
            } else if (currentName.equals("B相电网功率因数最小值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_Min_B());
                }
            } else if (currentName.equals("C相电网功率因数最小值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_Min_C());
                }
            } else if (currentName.equals("A相电网功率因数平均值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_AVG_A());
                }
            } else if (currentName.equals("B相电网功率因数平均值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_AVG_B());
                }
            } else if (currentName.equals("C相电网功率因数平均值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getSystemPF_AVG_C());
                }
            } else if (currentName.equals("A相负载功率因数最大值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_Max_A());
                }
            } else if (currentName.equals("B相负载功率因数最大值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_Max_B());
                }
            } else if (currentName.equals("C相负载功率因数最大值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_Max_C());
                }
            } else if (currentName.equals("A相负载功率因数最小值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_Min_A());
                }
            } else if (currentName.equals("B相负载功率因数最小值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_Min_B());
                }
            } else if (currentName.equals("C相负载功率因数最小值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_Min_C());
                }
            } else if (currentName.equals("A相负载功率因数平均值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_AVG_A());
                }
            } else if (currentName.equals("B相负载功率因数平均值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_AVG_B());
                }
            } else if (currentName.equals("C相负载功率因数平均值")) {
                for (int j = 0, length2 = reportDateModel1days.size(); j < length2; j++) {
                    yValues.add(reportDateModel1days.get(j).getLoadPF_AVG_C());
                }
            }

            lineChartEntity.setxAxisValue(xValues);//x坐标数据;
            lineChartEntity.setyAxisValue(yValues);//y 坐标数据
            lineChartEntity.setColor(legendEntityList.get(i).color);//颜色

            lineChartEntityList.add(lineChartEntity);
        }


        return lineChartEntityList;
    }

    private void initData() {
        checkBoxList = new ArrayList<>();
        list_arrays.add(powerFactor_array);
        list_arrays.add(activePower_array);
        list_arrays.add(reactivePower_array);
    }

    private void initListener() {
        chartsTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                Toast.makeText(mContext, "点击了" + i + "+" + l, Toast.LENGTH_SHORT).show();
                setCheckBoxsView(i);
            }

            private void setCheckBoxsView(int i) {
                currentArrayID = i;
                mTitleX = "日期（号）";
                switch (i) {
                    case 0:
                        mTitleY = "功率因数";
                        chartsCheckLl.setVisibility(View.VISIBLE);
                        chartsCheck1.setText("A相电网功率因数");
                        chartsCheck2.setText("B相电网功率因数");
                        chartsCheck3.setText("C相电网功率因数");
                        chartsCheck4.setText("A相负载功率因数");
                        chartsCheck5.setText("B相负载功率因数");
                        chartsCheck6.setText("C相负载功率因数");
                        break;
                    case 1:
                        mTitleY = "有功功率";
                        chartsCheckLl.setVisibility(View.GONE);
                        chartsCheck1.setText("A相电网有功功率");
                        chartsCheck2.setText("B相电网有功功率");
                        chartsCheck3.setText("C相电网有功功率");
                        break;
                    case 2:
                        mTitleY = "无功功率";
                        chartsCheckLl.setVisibility(View.GONE);
                        chartsCheck1.setText("A相电网无功功率");
                        chartsCheck2.setText("B相电网无功功率");
                        chartsCheck3.setText("C相电网无功功率");
                        break;
                }
                chartsCheck1.setChecked(false);
                chartsCheck2.setChecked(false);
                chartsCheck3.setChecked(false);
                chartsCheck4.setChecked(false);
                chartsCheck5.setChecked(false);
                chartsCheck6.setChecked(false);
                chartsMax.setChecked(false);
                chartsMin.setChecked(false);
                chartsAvg.setChecked(false);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    ArrayAdapter<String> stringArrayAdapter;

    public void initView() {
        stringArrayAdapter = new ArrayAdapter<String>(mContext, R.layout.spinner_item, new String[]{"功率因数", "有功功率", "无功功率"});
        chartsTypeSpinner.setAdapter(stringArrayAdapter);
        chartsTime.setText(startDate);
        checkBoxList.add(chartsCheck1);
        checkBoxList.add(chartsCheck2);
        checkBoxList.add(chartsCheck3);
        checkBoxList.add(chartsCheck4);
        checkBoxList.add(chartsCheck5);
        checkBoxList.add(chartsCheck6);
    }

    /**
     * 重写SwipeRefreshLayout.OnRefreshListener的OnRefresh方法
     * 在这里面去做下拉刷新的操作
     */
    @Override
    public void onRefresh() {
        updateData();
    }

    private void updateData() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("EventWarning____onActivityCreated");
    }


    @Override
    public void onStart() {
        super.onStart();
        System.out.println("EventWarning____onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("Event\nWarning____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();

        System.out.println("EventWarning____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();

        System.out.println("EventWarning____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("EventWarning____onDestroyView");
        unbinder.unbind();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        System.out.println("EventWarning____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("EventWarning____onDetach");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

        }
    }

    private void showDiolg(String commandName) {
        Dialog_Alert diolgAlert = new Dialog_Alert();
        diolgAlert.setCommandName(commandName);
        diolgAlert.show(this.getFragmentManager(), "");
    }

    private List<String> checkedArray = new ArrayList<>();

    @OnClick({R.id.data_charts_draw, R.id.charts_time, R.id.charts_max, R.id.charts_min, R.id.charts_avg, R.id.charts_check_1, R.id.charts_check_2, R.id.charts_check_3, R.id.charts_check_4, R.id.charts_check_5, R.id.charts_check_6})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.charts_time:
                showDiolg_datePick("请选择查询时间");
                Dialog_datePickUtil.setDiolgAlertListener(new Dialog_datePickUtil.Diolg_datePickListener() {
                    @Override
                    public void onClink(String date) {
                        postEventDate(date, EventBusModel_Date.START_DATE);
                        Toast.makeText(mContext, "" + date, Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.charts_max:
//                Toast.makeText(mContext, "max", Toast.LENGTH_SHORT).show();
                break;
            case R.id.charts_min:
                break;
            case R.id.charts_avg:
                break;
            case R.id.data_charts_draw:
//                initLine();
                drawLineChart(chartsChart, mTitleX, mTitleY);
                break;
        }


        list_arrays_selected.clear();
        if (chartsMax.isChecked()) {
            for (int i = 0; i < checkBoxList.size(); i++) {
                if (checkBoxList.get(i).isChecked()) {
                    list_arrays_selected.add(list_arrays.get(currentArrayID)[i] + "最大值");
                }
            }
        }

        if (chartsMin.isChecked()) {
            for (int i = 0; i < checkBoxList.size(); i++) {
                if (checkBoxList.get(i).isChecked()) {
                    list_arrays_selected.add(list_arrays.get(currentArrayID)[i] + "最小值");
                }
            }

        }

        if (chartsAvg.isChecked()) {
            for (int i = 0; i < checkBoxList.size(); i++) {
                if (checkBoxList.get(i).isChecked()) {
                    list_arrays_selected.add(list_arrays.get(currentArrayID)[i] + "平均值");
                }
            }
        }
        legendEntities.clear();
        for (int i = 0; i < list_arrays_selected.size(); i++) {
            Log.e("check", "" + list_arrays_selected.get(i));
            LegendEntity legendEntity = new LegendEntity();
            legendEntity.name = list_arrays_selected.get(i);
//            Random random = new Random();
//            int r = random.nextInt(256);
//            int g = random.nextInt(256);
//            int b = random.nextInt(256);
//            legendEntity.color = Color.rgb(r, g, b);

            legendEntity.color = colors[i];
            legendEntities.add(legendEntity);

        }
        legend_view.removeAllViews();

        for (int i = 0; i < legendEntities.size(); i++) {
            View viewItem = LayoutInflater.from(mContext).inflate(R.layout.data_chart_view_item, null);
            //绘制图例
            viewItem.findViewById(R.id.chart_view_item_color).setBackgroundColor(legendEntities.get(i).color);
            ((TextView) viewItem.findViewById(R.id.chart_view_item_name)).setText(legendEntities.get(i).name);
            legend_view.addView(viewItem);
        }

        Log.e("check", "##################################################");

    }

    private void showDiolg_datePick(String commandName) {
        Dialog_datePickUtil datePickUtil = new Dialog_datePickUtil();
        datePickUtil.setCommandName(commandName, Dialog_datePickUtil.yyyy_MM);
        datePickUtil.show(this.getFragmentManager(), "");
    }

    private void postEventDate(String date, String type) {
        EventBusModel_Date eventBusModel_date = new EventBusModel_Date();
        eventBusModel_date.dateType = type;
        eventBusModel_date.date = date;
        EventBus.getDefault().post(eventBusModel_date);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataUpdate(EventBusModel_Date eventBusModel_date) {

        if (EventBusModel_Date.START_DATE.equals(eventBusModel_date.dateType)) {
            startDate = eventBusModel_date.date;
            chartsTime.setText(startDate);
        }
    }
}
